package com.hxqh.bo.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hxqh.bo.bean.FpsTradeLog;
import com.hxqh.bo.dao.FpsTradeLogDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * FpsTradeLog entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.hxqh.bo.bean.FpsTradeLog
 * @author MyEclipse Persistence Tools
 */

public class FpsTradeLogDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(FpsTradeLogDAO.class);
	// property constants
	public static final String POLICY_ID = "policyId";
	public static final String FUTURES_CODE = "futuresCode";
	public static final String TRADE_NUM = "tradeNum";
	public static final String TRADE_PRICE = "tradePrice";
	public static final String TRADE_DATE_KEY = "tradeDateKey";
	public static final String SELL = "sell";
	public static final String DIRECTION = "direction";
	public static final String POLICY_NAME = "policyName";

	protected void initDao() {
		// do nothing
	}
	
	public Integer isExistsTradeLog(final int policyid, final double tradeDateKey, final int sell, final int direction) {
		return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				
				String sql = "select count(1) num from fps_trade_log" +
						" where policy_id = " + policyid +
						" and trade_date_key = " + tradeDateKey +
						" and sell = " + sell +
						" and direction = " + direction; 
				
				SQLQuery q = arg0.createSQLQuery(sql);
				
				q.addScalar("num", Hibernate.INTEGER);
				
				return q.uniqueResult();
			}
		});
	}
	
	public List getTop5(final String sql) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				log.info(sql);
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("POLICY_ID",Hibernate.INTEGER);
				return q.list();
			}
		});
	}
	
	public List getMostActiveTop5Id() {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				
				String sql = "select POLICY_ID, count(POLICY_ORDER_NO) POLICY_ORDER_NO" +
						" from fps_trade_log " +
						" where date_sub(curdate(), INTERVAL 30 DAY) <= date(`TRADE_DATE`)" +
						" group by POLICY_ID" +
						" order by POLICY_ORDER_NO desc limit 3";
				System.out.println(sql);
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("POLICY_ID",Hibernate.INTEGER);
				return q.list();
			}
		});
	}
	
	public List findLastPrices(final Integer policyId, final Integer action, final Integer tradeNum) {
		List executeFind = getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String sql = "select trade_price from fps_trade_log where policy_id = " + policyId +
						" and trade_action = " + action +
						" order by trade_log_id desc limit " + tradeNum;
				
				SQLQuery q = arg0.createSQLQuery(sql);
				
				q.addScalar("trade_price", Hibernate.DOUBLE);
				
				return q.list();
			}
			
		});
		return executeFind;
	}
	

	public void save(FpsTradeLog transientInstance) {
		log.debug("saving FpsTradeLog instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(FpsTradeLog persistentInstance) {
		log.debug("deleting FpsTradeLog instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public FpsTradeLog findById(java.lang.Long id) {
		log.debug("getting FpsTradeLog instance with id: " + id);
		try {
			FpsTradeLog instance = (FpsTradeLog) getHibernateTemplate().get(
					"com.hxqh.bo.bean.FpsTradeLog", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(FpsTradeLog instance) {
		log.debug("finding FpsTradeLog instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding FpsTradeLog instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from FpsTradeLog as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByPolicyId(Object policyId) {
		return findByProperty(POLICY_ID, policyId);
	}

	public List findByFuturesCode(Object futuresCode) {
		return findByProperty(FUTURES_CODE, futuresCode);
	}

	public List findByTradeNum(Object tradeNum) {
		return findByProperty(TRADE_NUM, tradeNum);
	}

	public List findByTradePrice(Object tradePrice) {
		return findByProperty(TRADE_PRICE, tradePrice);
	}

	public List findByTradeDateKey(Object tradeDateKey) {
		return findByProperty(TRADE_DATE_KEY, tradeDateKey);
	}

	public List findBySell(Object sell) {
		return findByProperty(SELL, sell);
	}

	public List findByDirection(Object direction) {
		return findByProperty(DIRECTION, direction);
	}

	public List findByPolicyName(Object policyName) {
		return findByProperty(POLICY_NAME, policyName);
	}

	public List findAll() {
		log.debug("finding all FpsTradeLog instances");
		try {
			String queryString = "from FpsTradeLog";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public FpsTradeLog merge(FpsTradeLog detachedInstance) {
		log.debug("merging FpsTradeLog instance");
		try {
			FpsTradeLog result = (FpsTradeLog) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(FpsTradeLog instance) {
		log.debug("attaching dirty FpsTradeLog instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(FpsTradeLog instance) {
		log.debug("attaching clean FpsTradeLog instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static FpsTradeLogDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (FpsTradeLogDAO) ctx.getBean("FpsTradeLogDAO");
	}
}